package com.spc.car.service.sys.impl;

import com.spc.car.common.exception.CustomException;
import com.spc.car.data.entity.sys.*;
import com.spc.car.data.service.sys.*;
import com.spc.car.service.domain.po.sys.UserPO;
import com.spc.car.service.sys.UserService;
import com.spc.car.service.util.EncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysPostService sysPostService;

    @Autowired
    SysUserRoleService userRoleService;

    @Autowired
    SysUserPostService userPostService;

    @Autowired
    SysConfigService configService;


    /**
     * 新增保存用户信息
     *
     * @param userPO 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean save(UserPO userPO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userPO, sysUser);

        // 新增用户信息
        boolean result = sysUserService.saveOrUpdate(sysUser);
        if (result) {
            if (null != userPO.getUserId()) {
                // 删除用户与角色关联
                userRoleService.deleteByUserId(sysUser.getUserId());
                // 删除用户与岗位关联
                userPostService.deleteByUserId(sysUser.getUserId());
            }
            // 新增用户与角色管理
            if (CollectionUtils.isNotEmpty(userPO.getRoleIds())) {
                List<SysUserRole> userRoles = new ArrayList<>();
                userPO.getRoleIds().forEach(roleId ->{
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRole.setRoleId(roleId);
                    userRoles.add(sysUserRole);
                });
                userRoleService.saveBatch(userRoles);
            }

            // 新增用户与岗位管理
            if (CollectionUtils.isNotEmpty(userPO.getPostIds())) {
                List<SysUserPost> userPosts = new ArrayList<>();
                userPO.getPostIds().forEach(postId -> {
                    SysUserPost sysUserPost = new SysUserPost();
                    sysUserPost.setUserId(sysUser.getUserId());
                    sysUserPost.setPostId(postId);
                    userPosts.add(sysUserPost);
                });
                userPostService.saveBatch(userPosts);
            }
        }
        return result;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户名
     * @return 结果: 角色间用逗号分隔
     */
    @Override
    public String getRoleByUserId(@NotNull Long userId) {
        List<SysRole> roles = sysRoleService.listRoleByUserId(userId);
        List<String> roleNames = roles.stream().map(SysRole::getRoleName).collect(Collectors.toList());
        return StringUtils.join(roleNames, ",");
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userId 用户ID
     * @return 结果: 岗位名称以逗号分隔
     */
    @Override
    public String getUserPostGroup(@NotNull Long userId) {
        List<SysPost> posts = sysPostService.listPostByUserId(userId);
        List<String> roleNames = posts.stream().map(SysPost::getPostName).collect(Collectors.toList());
        return StringUtils.join(roleNames, ",");
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (CollectionUtils.isEmpty(userList)) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try {
                // 验证是否存在这个用户
                SysUser u = sysUserService.selectUserByUserName(user.getUserName());
                if (Objects.isNull(u)) {
                    user.setPassword(EncryptUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    sysUserService.save(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    sysUserService.saveOrUpdate(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
